<template>
  <div class="app-container">
    <PlatformHeader />
    <el-row :gutter="20" style="height: calc(100vh - 72px);padding-top: 10px;padding-bottom: 10px">
      <div class="right-pane">
        <!-- 查询表单 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          class="search-form custom-form"
        >
          <el-form-item label="年份" prop="year" class="form">
            <el-select
              popper-class="custom-select-dropdown"
              v-model="queryParams.year"
              placeholder="选择年份"
              clearable
              style="width: 120px"
              class="year-select"
            >
              <el-option
                v-for="item in yearOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status"  class="form">
            <el-select
              popper-class="custom-select-dropdown"
              v-model="queryParams.status"
              placeholder="全部状态"
              clearable
              style="width: 120px"
              class="status-select"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="监测点" prop="testpoint"  class="form">
            <el-input
              v-model="queryParams.testpoint"
              placeholder="输入监测点名称"
              clearable
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              class="search-btn action-btn"
            >
              搜索
            </el-button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
              class="reset-btn action-btn"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table
          v-loading="loading"
          :data="testpointList"
          class="custom-table"
        >
          <el-table-column label="省" align="center" prop="sheng" :show-overflow-tooltip="true"/>
          <el-table-column label="市" align="center" prop="shi" :show-overflow-tooltip="true"/>
          <el-table-column label="区" align="center" prop="qu" :show-overflow-tooltip="true"/>
          <el-table-column label="监测点" align="center" prop="testpoint"/>
          <el-table-column label="GPS坐标" align="center" prop="gps" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" align="center" prop="createtime"/>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              {{ statusText(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px;">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-location"
                @click="showOnMap(scope.row)"
                class="table-action-btn map-btn"
              >
                GPS审核
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
          class="custom-pagination"
        />
      </div>
    </el-row>

    <!-- 高德地图弹窗 -->
    <el-dialog
      title="GPS坐标位置审核"
      :visible.sync="mapVisible"
      width="80%"
      top="5vh"
      custom-class="map-dialog custom-dialog"
    >
      <div id="map-container" style="width:100%;height:70vh;"></div>
      <div slot="footer" class="dialog-footer">
        <el-form
          ref="mapForm"
          :model="form"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="审核状态" prop="status" :rules="[{ required: true, message: '请选择审核状态', trigger: 'change' }]">
            <el-radio-group v-model="form.status">
              <el-radio label="1">通过</el-radio>
              <el-radio label="2">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <el-button @click="mapVisible = false" class="dialog-btn cancel-btn dialog-cancel-btn">取 消</el-button>
        <el-button type="primary" @click="submitForm" class="dialog-btn confirm-btn dialog-confirm-btn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reviewgps, updateTReviewgps } from "@/api/monitormanage/testpoint";
import PlatformHeader from '../../../components/PlatformHeader/index.vue';

export default {
  name: "GpsAudit",
  components: { PlatformHeader },
  data() {
    return {
      loading: true,
      total: 0,
      testpointList: [],
      yearOptions: [],
      statusOptions: [
        { value: null, label: '全部状态' },
        { value: '0', label: '未审核' },
        { value: '1', label: '审核通过' },
        { value: '2', label: '审核不通过' }
      ],
      mapVisible: false,
      map: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        year: new Date().getFullYear().toString(),
        status: null,
        testpoint: null,
        orgId: null,
      },
      form: {
        id: null,
        testpoint: '',
        gps: '',
        status: '',
        remark: ''
      },
      currentRow: null, // 用于保存当前点击的行数据
    };
  },
  created() {
    this.initYearOptions();
    this.getList();
    this.loadAMapScript();
  },
  methods: {
    loadAMapScript() {
      const key = 'dca79689d6b7a82fe0d937399ad84608';
      const script = document.createElement('script');
      script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${key}&plugin=AMap.Geocoder`;
      script.onerror = () => {
        console.error('高德地图加载失败');
      };
      document.head.appendChild(script);
    },

    showOnMap(row) {
      if (!row.gps) {
        this.$message.warning('该监测点没有GPS坐标数据');
        return;
      }
      this.currentRow = row;
      const coordinates = this.parseGPS(row.gps);
      if (!coordinates) {
        this.$message.error('GPS坐标格式不正确');
        return;
      }

      this.form = {
        id: row.id,
        testpoint: row.testpoint,
        gps: row.gps,
        status: '',
        remark: '通过地图审核'
      };

      this.mapVisible = true;
      this.$nextTick(() => {
        this.initMap(coordinates, row.testpoint);
      });
    },

    initMap(coordinates, title) {
      if (!window.AMap) {
        this.$message.error('高德地图API未加载成功');
        return;
      }

      if (this.map) {
        this.map.destroy();
      }

      this.map = new AMap.Map('map-container', {
        zoom: 15,
        center: [coordinates.lng, coordinates.lat],
        viewMode: '2D'
      });

      const marker = new AMap.Marker({
        position: new AMap.LngLat(coordinates.lng, coordinates.lat),
        title: title
      });
      this.map.add(marker);

      const infoWindow = new AMap.InfoWindow({
        content: `<div style="padding:5px;">
                   <div>监测点: ${title}</div>
                   <div>坐标: ${coordinates.lng}, ${coordinates.lat}</div>
                 </div>`,
        offset: new AMap.Pixel(0, -30)
      });
      infoWindow.open(this.map, marker.getPosition());
    },

    parseGPS(gpsStr) {
      // 尝试解析度分秒格式：113°15′41.34″,23°07′41.24″
      const dmsPattern = /([\d.]+)°([\d.]+)′([\d.]+)″\s*,\s*([\d.]+)°([\d.]+)′([\d.]+)″/;
      const dmsMatch = gpsStr.match(dmsPattern);
      if (dmsMatch) {
        const lng = parseFloat(dmsMatch[1]) + parseFloat(dmsMatch[2])/60 + parseFloat(dmsMatch[3])/3600;
        const lat = parseFloat(dmsMatch[4]) + parseFloat(dmsMatch[5])/60 + parseFloat(dmsMatch[6])/3600;
        return { lng, lat };
      }

      // 尝试解析十进制格式：113.261483,23.128122
      const decimalPattern = /([\d.]+)\s*,\s*([\d.]+)/;
      const decimalMatch = gpsStr.match(decimalPattern);
      if (decimalMatch) {
        return { lng: parseFloat(decimalMatch[1]), lat: parseFloat(decimalMatch[2]) };
      }

      return null;
    },

    initYearOptions() {
      const currentYear = new Date().getFullYear();
      this.yearOptions = Array.from({length: 5}, (_, i) => (currentYear - i).toString());
    },

    statusText(status) {
      const map = {
        '0': '未审核',
        '1': '审核通过',
        '2': '审核不通过'
      };
      return map[status] || '';
    },

    getList() {
      this.loading = true;
      reviewgps(this.queryParams).then(response => {
        this.testpointList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.year = new Date().getFullYear().toString();
      this.queryParams.status = null;
      this.handleQuery();
    },

    submitForm() {
      this.$refs.mapForm.validate(valid => {
        if (valid) {
          if (!this.form.status) {
            this.$message.warning('请选择审核状态');
            return;
          }
          //alert(this.form.status)
          const submitData = {
            id: this.form.id,
            gps: this.form.gps,
            status: this.form.status,
            remark: this.form.remark
          };
          this.currentRow.status = this.form.status;
          updateTReviewgps(this.currentRow).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.mapVisible = false;
            this.getList();
          }).catch(() => {
            this.$modal.msgError("审核失败");
          });
        }
      });
    }
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: url('../../assets/images/bgn.png');
  background-size: 100% 100%;
  padding: 16px;
  box-sizing: border-box;
  padding-top: 0;

  .el-row {
    .right-pane {
      background: transparent;
      border-radius: 8px;
      padding: 15px;
      width: 100%;
    }
  }
}

.search-form {
  margin-bottom: 15px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;

  .el-form-item {
    margin-bottom: 0;
    margin-right: 15px;
  }
}

::v-deep .el-table {
  background: transparent;
  border-radius: 12px;
  overflow: hidden;

  .el-table__header-wrapper {
    border-radius: 12px;
    overflow: hidden;

    th:first-child {
      border-top-left-radius: 12px;
    }
    th:last-child {
      border-top-right-radius: 12px;
    }
  }

  .el-table__body-wrapper {
    border-radius: 0 0 12px 12px;

    tr {
      td:first-child {
        border-bottom-left-radius: 12px;
      }
      td:last-child {
        border-bottom-right-radius: 12px;
      }
    }

    tr.el-table__row {
      td:first-child {
        border-top-left-radius: 12px;
        border-bottom-left-radius: 12px;
      }
      td:last-child {
        border-top-right-radius: 12px;
        border-bottom-right-radius: 12px;
      }
    }
  }
}

::v-deep .el-table th.el-table__cell {
  border: none;
}

.el-table::before {
  height: 0;
}

::v-deep .el-table th.el-table__cell.is-leaf {
  border-bottom: none;
}

::v-deep .el-table th {
  background: #f7e797;
  color: #1e4f91;
  font-weight: bold;
  font-size: 18px;
  height: 30px;
  line-height: 30px;
}

::v-deep .el-table__row {
  td {
    border: none;
  }
}

::v-deep .el-table__row:nth-child(odd) {
  background: linear-gradient(90deg, #99e8ff, #4f85ff);
}

::v-deep .el-table__row:nth-child(even) {
  background: linear-gradient(90deg, #4f85ff, #99e8ff);
}

::v-deep .el-table td {
  color: #000;
  font-size: 18px;
  padding: 12px 8px;
}

::v-deep .el-table__body {
  border-collapse: separate !important;
  border-spacing: 0 5px !important;
}

::v-deep .el-table__body tr:hover > td {
  background: #9ef7c5 !important;
}

::v-deep .el-table .el-button--mini {
  color: #000 !important;
  font-size: 16px;
  font-weight: 400;
}

::v-deep .el-table .cell {
  line-height: 35px;
  height: 35px;
}

::v-deep .pagination {
  margin-top: 16px;
  padding: 10px 0;
  background-color: #f8fbff;
  border-radius: 8px;
}

::v-deep .pagination-container {
  background: transparent;
}

::v-deep .el-pagination {
  color: #fff !important;
}

::v-deep .el-pagination__total {
  color: #fff !important;
}

::v-deep .el-pagination__jump {
  color: #fff !important;
}

.action-btn {
  border-radius: 22px;
  font-weight: 600;
  font-size: 16px;
  padding: 10px 20px;
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(66, 133, 244, 0.3);
}

.search-btn {
  background: linear-gradient(135deg, #b4cdeb, #2f6bcc);
  color: #fff;
  &:hover {
    background: linear-gradient(135deg, #5aa2f8, #3a8ef6);
    box-shadow: 0 6px 14px rgba(58, 142, 246, 0.5);
  }
}

.reset-btn {
  background: linear-gradient(135deg, #df9f3f, #edc73d);
  color: #fff;
  &:hover {
    background: linear-gradient(135deg, #ffcc80, #ffb74d);
    box-shadow: 0 6px 14px rgba(255, 183, 77, 0.5);
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;

  .el-button {
    min-width: 120px;
    height: 40px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 1px;
    transition: all 0.3s;
    margin: 0;
  }
  .dialog-cancel-btn {
    border: none;
    background: linear-gradient(135deg, #aed7ff, #80bcf9);
    color: #fff;
    font-size: 16px;
    box-shadow: 0 6px 14px rgb(128 188 249 / 50%);
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .dialog-confirm-btn {
    background: linear-gradient(90deg, #4f85ff, #6a8cff);
    border: none;
    color: #fff;
    font-size: 16px;
    box-shadow: 0 6px 14px rgb(128 188 249 / 50%);
    &:hover {
      background: linear-gradient(90deg, #3a73ff, #4f85ff);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(79, 133, 255, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }
}

::v-deep .map-dialog {
  .el-dialog__header {
    background: linear-gradient(90deg, #8caefb, #0160FA);
    padding: 15px 20px;
    margin: 0;
    border-bottom: none;

    .el-dialog__title {
      color: #fff;
      font-size: 18px;
      font-weight: 600;
    }

    .el-dialog__headerbtn {
      top: 15px;

      .el-dialog__close {
        color: #fff;
      }
    }
  }

  .el-dialog__body {
    padding: 0 !important;
  }
}

::v-deep {
  .custom-dialog {
    border-radius: 16px !important;
    overflow: hidden!important;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2)!important;
    background: linear-gradient(145deg, #f5f7fa, #e4e8f0)!important;

    .el-dialog__header {
      background: linear-gradient(90deg, #8caefb, #0160FA)!important;
      padding: 20px!important;
      margin: 0!important;
      border-bottom: none!important;

      .el-dialog__title {
        color: #fff!important;
        font-size: 20px!important;
        font-weight: 600!important;
        letter-spacing: 1px!important;
      }

      .el-dialog__headerbtn {
        top: 20px!important;
        right: 20px!important;

        .el-dialog__close {
          color: #fff!important;
          font-size: 20px!important;
        }
      }
    }

    .el-dialog__body {
      background: linear-gradient(145deg, #e6f0ff, #bad2ff)!important;
      color: #333!important;
    }

    .el-dialog__footer {
      padding: 6px!important;
      background: linear-gradient(145deg, #e6f0ff, #a2c3ff)!important;
      border-top: 1px solid rgba(79, 133, 255, 0.1)!important;
      border-radius: 0 0 16px 16px!important;
    }
  }

  .custom-dialog .el-input__inner,
  .custom-dialog .el-textarea__inner {
    color: #000 !important;
    border: 1px solid rgba(79, 133, 255, 0.3)!important;
    background-color: rgba(255, 255, 255, 0.7)!important;
  }

  .custom-dialog .el-input__inner:focus,
  .custom-dialog .el-textarea__inner:focus {
    border-color: #409eff !important;
    box-shadow: 0 0 5px rgba(64, 158, 255, 0.6) !important;
    background-color: rgba(255, 255, 255, 0.9) !important;
  }
}

::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  border-radius: 4px;
  background-color: rgb(1 96 250);
}

::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #0080ff;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #C7C9CC;
}

::v-deep .el-form-item__label {
  font-size: 20px;
}

::v-deep .el-radio__label {
  font-size: 20px;
}
::v-deep .dialog-form{
  padding-top: 20px;
}
.form ::v-deep .el-form-item__label {
  color: #fff; /* 例如：color: #ff0000; 设置为红色 */
  font-weight: bold; /* 如果需要，也可以同时修改其他样式，如字体粗细 */
}
</style>
